package com.jlu155.CourseManager.controller;

import com.jlu155.CourseManager.Bean.PageRequest;
import com.jlu155.CourseManager.Bean.PageResult;
import com.jlu155.CourseManager.entity.*;
import com.jlu155.CourseManager.repository.*;
import com.jlu155.CourseManager.service.CourseService;
import com.jlu155.CourseManager.service.StudentCourseService;
import com.jlu155.CourseManager.service.TeachClassService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
public class CourseController {
    private static final Logger log = LoggerFactory.getLogger(CourseController.class);
    @Autowired
    private CourseRepository courseRepository;
    @Autowired
    private CourseService courseService;

    @Autowired
    private StudentCourseRepository studentCourseRepository;
    @Autowired
    private StudentCourseService studentCourseService;

    @Autowired
    private TeachClassRepository teachClassRepository;
    @Autowired
    private TeachClassService teachClassService;
    @Autowired
    private SessionRepository sessionRepository;
    @Autowired
    private CollegeRepository collegeRepository;
    @GetMapping("/getAllCourses")
    public List<Course> getAllCourses(){
        return courseRepository.findAllCourses();
    }
    @PostMapping("/getPageCourses")
    public PageResult<Course> getPageCourses(@RequestBody PageRequest pageRequest){

        return courseService.getCoursePage(pageRequest);
    }

    @PostMapping("/getSelectedCourses")
    public ResponseEntity<PageResult<StudentCourse>> getSelectedCourses(@RequestBody PageRequest pageRequest,HttpSession session){
        Integer sid= (Integer) session.getAttribute("student_id");
        Integer tid= (Integer) session.getAttribute("teacher_id");
        if(sid==null&&tid==null){
            return ResponseEntity.badRequest().body(null);
        }
        return ResponseEntity.ok().body(studentCourseService.getSelectedCoursesPage(pageRequest));
    }
    @GetMapping("/getSessionByTcId")
    public List<Session> getSessionByTcId(@RequestParam Integer tc_id){
        return sessionRepository.findSessionsByTcId(tc_id);
    }

    @RequestMapping("/selectTeachClass")
    public ResponseEntity selectTeachClass(@RequestBody Integer tc_id, HttpSession session){
        Integer sid= (Integer) session.getAttribute("student_id");
        //System.out.println(sid);
        if(sid==null){
            return ResponseEntity.badRequest().body("登录失效");
        }
        String status=studentCourseService.chooseCourse(sid,tc_id);
        if(status.equals("ok")){
            return ResponseEntity.ok().body("选课成功");
        }else{
            return ResponseEntity.badRequest().body(status);
        }
    }


    @RequestMapping("/getPageTeachClass")
    public ResponseEntity<PageResult<TeachClass>> getPageTeachCLass(@RequestBody PageRequest pageRequest,HttpSession session){
        Integer teacher_id=(Integer)session.getAttribute("teacher_id");
        if(teacher_id==null){
            return ResponseEntity.badRequest().body(null);
        }
        if(pageRequest.getTid()==null){
            pageRequest.setTid(teacher_id);
        }
        return ResponseEntity.ok().body(teachClassService.getTeachClassPage(pageRequest));
    }
    @RequestMapping("/addTeachClass")
    public ResponseEntity addTeachClass(@RequestBody TeachClass teachClass,HttpSession session)
    {
        Integer teacher_id=(Integer)session.getAttribute("teacher_id");
        if(teacher_id==null){
            return ResponseEntity.badRequest().body("登录失效");
        }
        List<TeachClass> teachClassList=teachClassRepository.findTeachClassByTeacherId(teacher_id);
        for(TeachClass item:teachClassList){
            if(item.getCourse_id()==teachClass.getCourse_id()){
                return ResponseEntity.badRequest().body("错误：课程已存在");
            }
        }
        teachClassRepository.insertTeachClass(teachClass);
        return ResponseEntity.ok().body("增加教学班成功");
    }
    @RequestMapping("/deleteStudentCourse")
    public ResponseEntity deleteStudentCourse(@RequestBody PageRequest pageRequest, HttpSession session){
        Integer sid= (Integer) session.getAttribute("student_id");
        Integer tid= (Integer) session.getAttribute("teacher_id");
        //System.out.println(sid);
        if(sid==null&&tid==null){
            return ResponseEntity.badRequest().body("登录失效");
        }
        if(pageRequest.getSid()==null) pageRequest.setSid(sid);
        if(studentCourseRepository.deleteStudentCourse(pageRequest.getSid(), pageRequest.getTc_id())) return ResponseEntity.ok().body("退选成功");
        else return ResponseEntity.badRequest().body("退选失败");
    }

    @PostMapping("/insertCourse")
    public ResponseEntity insertCourse(@RequestBody Course course,HttpSession session){
        Integer teacher_type=(Integer)session.getAttribute("teacher_type");
        if(teacher_type!=1)
            return ResponseEntity.badRequest().body("权限不足");
        if(courseRepository.findCourseById(course.getCourse_id())!=null)
            return ResponseEntity.badRequest().body("错误，课程已存在");
        courseRepository.insertCourse(course);
        return ResponseEntity.ok().body("增加课程成功");
    }

    @PostMapping("/insertSession")
    public ResponseEntity insertSession(@RequestBody Session tsession,HttpSession session){
        Integer teacher_type=(Integer)session.getAttribute("teacher_type");
        if(teacher_type!=1)
            return ResponseEntity.badRequest().body("权限不足");
        if(sessionRepository.findSessionById(tsession.getSession_id())!=null)
            return ResponseEntity.badRequest().body("错误，开课已存在");
        sessionRepository.insertSession(tsession);
        return ResponseEntity.ok().body("增加开课成功");
    }
    @PostMapping("/deleteSession")
    public ResponseEntity deleteSession(@RequestBody Integer session_id){
        try{
            sessionRepository.deleteSession(session_id);
            return ResponseEntity.ok(true);
        } catch (Exception e){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    @PostMapping("/updateCourse")
    public ResponseEntity updateCourse(@RequestBody Course course,HttpSession session){
        Integer teacher_type=(Integer)session.getAttribute("teacher_type");
        if(teacher_type!=1)
            return ResponseEntity.badRequest().body("权限不足");
        Course tcourse=courseRepository.findCourseById(course.getCourse_id());
        if(tcourse==null)
            return ResponseEntity.badRequest().body("错误，课程不存在");
        courseRepository.updateCourse(course);
        return ResponseEntity.ok().body("修改课程成功");
    }


    @PostMapping("/deleteCourse")
    public ResponseEntity deleteCourse(@RequestBody Integer course_id){
        try{
            courseRepository.deleteCourse(course_id);
            return ResponseEntity.ok(true);
        } catch (Exception e){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    @PostMapping("/updateTeachClass")
    public ResponseEntity updateTeachCLass(@RequestBody TeachClass teachClass,HttpSession session){
        Integer teacher_type=(Integer)session.getAttribute("teacher_type");
        if(teacher_type!=1)
            return ResponseEntity.badRequest().body("权限不足");
        teachClassRepository.updateTeachClass(teachClass);
        return ResponseEntity.ok().body("修改教学班成功");
    }
    @PostMapping("/insertTeachClass")
    public ResponseEntity insertTeachClass(@RequestBody TeachClass teachClass,HttpSession session){
        Integer teacher_type=(Integer)session.getAttribute("teacher_type");
        if(teacher_type!=1)
            return ResponseEntity.badRequest().body("权限不足");
        teachClassRepository.insertTeachClass(teachClass);
        return ResponseEntity.ok().body("增加课程成功");
    }
    @PostMapping("/deleteTeachClass")
    public ResponseEntity deleteTeachClass(@RequestBody Integer tc_id){
        try{
            teachClassRepository.deleteTeachClass(tc_id);
            return ResponseEntity.ok(true);
        } catch (Exception e){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    @RequestMapping("/updateStudentCourse")
    public ResponseEntity updateStudentCourse(@RequestBody StudentCourse sc,HttpSession session){
        Integer sid= (Integer) session.getAttribute("student_id");
        Integer tid= (Integer) session.getAttribute("teacher_id");
        //System.out.println(sid);
        if(sid==null&&tid==null){
            return ResponseEntity.badRequest().body("登录失效");
        }

        if(studentCourseRepository.updateStudentCourse(sc)) return ResponseEntity.ok().body("更新成功");
        else return ResponseEntity.badRequest().body("更新失败");
    }
    @RequestMapping("/getAllColleges")
    public ResponseEntity<List<College>> getAllCollege(){
        return ResponseEntity.ok().body(collegeRepository.findAllColleges());
    }
    @RequestMapping("/logout")
    public ResponseEntity logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate(); // 销毁会话
        }
        return ResponseEntity.ok().body(null);
    }

}
